<template lang="pug">
.view.cp-manage-train-courseman.fix-flex-pos
  .left-wrap(v-loading="treeLoading")
    .tree-title
      span.text {{ currentNode ? currentNode.name : null }}
      span.right-btn
        el-tooltip(content="新建")
          i.icon-act.el-icon-plus(@click="createDir")
        el-tooltip(content="编辑")
          i.icon-act.el-icon-edit(@click="editDir")
        el-tooltip(content="删除")
          i.icon-act.el-icon-delete(@click="deleteDir")
    el-tree.tree-warp(
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      @node-click="nodeClick")
      .custom-tree(slot-scope="{ node, data }")
        p(:class="{active: currentNode && currentNode.id === data.id}") {{ data.name }}
  el-dialog(
    :title="tdTitle"
    width="20%"
    :visible.sync="tdVisible")
    el-input(
      v-model="tdNodeName"
      placeholder="请输入分类名称")
    .dialog-footer(slot="footer")
      el-button(@click="treeCancel") 取消
      el-button(type="primary", @click="treeSave") 保存
  //- 查询
  .right-wrap
    el-form.mancou-search(:inline="true")
      el-form-item
        el-input(
          v-model="crsName",
          placeholder="编码/名称/描述",
          style="width: 200px")
      el-form-item(label="授课方式 :")
        el-select.select-width(v-model="crsForm", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in crsFormSelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="培训机构 :")
        el-select.select-width(v-model="crsAgency", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in agencySelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="创建人 :")
        el-select.select-width(v-model="crsCreator", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in empSelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="状态 :")
        el-select.select-width(v-model="status", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in statusSelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="可用性 :")
        el-select.select-width(v-model="crsAvailable", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in assessSelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item
        el-button(type="primary", @click="search") 搜索
      el-form-item
        el-button(type="primary", @click="createCourse") 新建
    //- 表格
    .mancou-table
      el-table(
        :data="dataList",
        highlight-current-row,
        v-loading="loadingData",
        size="mini",
        height="100%")
        el-table-column(show-overflow-tooltip, type="index", label="序号")
        el-table-column(show-overflow-tooltip, prop="code", label="编号")
        el-table-column(show-overflow-tooltip, prop="name", label="名称")
        el-table-column(show-overflow-tooltip, prop="type", label="课程分类")
          template(slot-scope="scope")
            span {{ scope.row.type | compare-list(crsTypeSelect) }}
        el-table-column(show-overflow-tooltip, prop="form", label="授课方式")
          template(slot-scope="scope")
            span {{ scope.row.form | compare-list(crsFormSelect) }}
        el-table-column(show-overflow-tooltip, prop="trainAgency", label="培训机构")
          template(slot-scope="scope")
            span {{ scope.row.trainAgency | compare-list(agencySelect) }}
        el-table-column(show-overflow-tooltip, prop="creator", label="创建人")
          template(slot-scope="scope")
            span {{ scope.row.creator | compare-list(empSelect) }}
        el-table-column(show-overflow-tooltip, prop="createTime", label="创建时间")
          template(slot-scope="scope")
            span {{ scope.row.createTime | date-format }}
        el-table-column(show-overflow-tooltip, prop="status", label="状态")
          template(slot-scope="scope")
            span {{ scope.row.status | compare-list(statusSelect) }}
        el-table-column(show-overflow-tooltip, prop="assess", label="可用性")
          template(slot-scope="scope")
            span {{ scope.row.assess | compare-list(assessSelect) }}
        el-table-column(label="操作", min-width="100px")
          template(slot-scope="scope")
            el-tooltip(content="查看")
              i.icon-act.el-icon-view(@click="viewCourse(scope.row)")
            el-tooltip(content="编辑")
              i.icon-act.el-icon-edit(@click="editCourse(scope.row)")
            el-tooltip(content="删除")
              i.icon-act.el-icon-delete(@click="deleteCourse(scope.row, scope.$index)")
    //- 分页
    el-pagination.mancou-pagination(
      background,
      layout="total, prev, pager, next, jumper",
      prev-text="上一页",
      next-text="下一页",
      @current-change="handleCurrentChange",
      :current-page="pageNum",
      :page-size="pageSize",
      :total="totalNum")
  //- 课程popup
  course-popup(
    :title="cfdiaTitle",
    :visible.sync="cfdiaVisible",
    :is-edit="cfdiaEdit",
    :parent-data="formData",
    @submit="onFormSubmit",
    @close="cfdiaVisible = false")
</template>

<script>
import { mapGetters } from 'vuex';
import TrainData from '@/data/train/trainManage';
import CoursePopup from './coursePopup';

export default {
  name: 'mancourseman',
  components: {
    CoursePopup
  },
  data() {
    return {
      // 左边部分
      treeLoading: false,
      treeData: [{
        id: '1',
        name: '',
        children: []
      }],
      // 当前tree节点
      currentNode: null,
      tdEdit: false,
      tdTitle: '新建分类',
      tdVisible: false,
      tdNodeName: null,
      // 右边部分
      loadingData: true,
      dataList: [],
      pageNum: 1,
      pageSize: 16,
      totalNum: 0,
      // 搜索条件
      crsName: null,
      crsForm: null,
      crsCreator: null,
      crsAgency: null,
      crsAvailable: null,
      status: null,
      // 弹出框
      cfdiaTitle: '新建课程',
      cfdiaVisible: false,
      cfdiaEdit: false,
      formData: {},
      // 搜索下拉框
      assessSelect: [
        { name: '启用', value: 0 },
        { name: '禁用', value: 1 }
      ],
      statusSelect: [
        { name: '待发布', value: 0 },
        { name: '已发布', value: 1 },
        { name: '已终止', value: 2 },
        { name: '已失效', value: 3 }
      ]
    };
  },
  computed: {
    ...mapGetters([
      'empSelect',
      'crsTypeSelect',
      'crsFormSelect',
      'agencySelect',
      'teacherSelect',
      'assignerSelect'
    ])
  },
  created() {
  },
  mounted() {
    this.loadTreeDetail();
  },
  methods: {
    // 处理tree详情
    dealTreeDetail(data) {
      // 根节点
      data[0].id = '1';
      this.dealChildren(data[0].children, data[0].id);
    },
    // 处理children的id
    dealChildren(array, prevPosi) {
      if (array && array.length) {
        // 使第一个为当前选择节点
        if (prevPosi.split('-').every(val => val == 1)) {
          this.currentNode = array[0];
        }
        // 重置节点初始位置信息
        array.forEach((item, index) => {
          const posi = `${prevPosi}-${index + 1}`;
          item.id = posi;
          this.dealChildren(item.children, posi);
        });
      }
    },
    // 获取tree detail
    loadTreeDetail() {
      this.treeLoading = true;
      setTimeout(() => {
        const data = TrainData.treeData;
        this.dealTreeDetail(data);
        this.treeData = data;
        this.treeLoading = false;
        this.loadDataList();
      }, 500);
    },
    // 取消编辑
    treeCancel() {
      this.tdVisible = false;
    },
    // 保存编辑
    treeSave() {
      if (!this.tdNodeName) {
        this.$message.info({ message: '请输入名称' });
        return;
      }
      this.treeLoading = true;
      setTimeout(() => {
        if (this.tdEdit) { // 修改分类
          this.currentNode.name = this.tdNodeName;
        } else { // 增加分类
          this.addNode(this.currentNode, this.tdNodeName);
        }
        this.treeLoading = false;
        this.tdVisible = false;
        this.$message({ message: '保存成功', type: 'success' });
      }, 500);
    },
    // 新增
    createDir() {
      if (this.currentNode) {
        this.tdEdit = false;
        this.tdTitle = '新建分类';
        this.tdVisible = true;
        this.tdNodeName = null;
      } else {
        this.$message.info('请先选择节点');
      }
    },
    // 编辑
    editDir() {
      if (this.currentNode) {
        this.tdEdit = true;
        this.tdTitle = '编辑分类';
        this.tdVisible = true;
        this.tdNodeName = this.currentNode.name;
      } else {
        this.$message.info('请先选择节点');
      }
    },
    // 删除
    deleteDir() {
      if (this.currentNode) {
        this.$confirm('所选分类及其子类将被删除，请确认是否删除?', '删除分类', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          /* const params = {
            orderNo: currentRow.orderNo
          };
          CheckoutApi.deleteInvCheckout(params).then((res) => {
            if (res.status === 0) {
              this.invCheckoutList.splice(index, 1);
              this.totalNum = this.totalNum - 1;
              this.$message({ message: '删除成功', type: 'success' });
            } else {
              this.$message.error(res.comment || '删除失败');
            }
          }); */
          this.removeNode(this.focusNode, this.currentNode);
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除' });
        });
      } else {
        this.$message.info('请先选择节点');
      }
    },
    // 添加节点
    addNode(data, name) {
      let id = '';
      const len = data.children && data.children.length;
      if (len) {
        const last = data.children[len - 1].id;
        const arr = last.split('-');
        const prev = arr[arr.length - 1];
        id = `${data.id}-${Number(prev) + 1}`;
      } else {
        id = `${data.id}-1`;
      }
      const newChild = { id, name, children: [] };
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
    },
    // 删除节点
    removeNode(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
      this.currentNode = null;
    },
    // 节点点击
    nodeClick(data, node) {
      this.currentNode = data;
      this.focusNode = node;
      if (data.id.split('-').length > 2) {
        this.loadDataList();
      }
    },
    // 整理参数
    filterParams() {
      const params = {
        crsName: this.crsName,
        crsForm: this.crsForm,
        crsCreator: this.crsCreator,
        crsAgency: this.crsAgency,
        crsAvailable: this.crsAvailable,
        status: this.status,
      };
      for (const key in params) {
        if (params[key] === null || params[key] === '') {
          delete params[key];
        }
      }
      return params;
    },
    // 取得表格数据
    loadDataList() {
      this.loadingData = true;
      // const params = this.filterParams();
      setTimeout(() => {
        this.dataList = TrainData.courseList;
        this.totalNum = 64;
        this.loadingData = false;
      }, 500);
    },
    // 搜索
    search() {
      if (this.pageNum !== 1) {
        this.pageNum = 1;
      }
      this.loadDataList();
    },
    // 页码改变
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.loadDataList();
    },
    // 新建课程
    createCourse() {
      this.cfdiaTitle = '新建课程';
      this.cfdiaEdit = true;
      this.formData = {
        // 组织架构选择
        accordOrgArr: [],
        // 角色选择
        accordRoleArr: [],
        // 黑名单
        accordBlackArr: [],
        // 课堂列表
        classList: [],
        studentList: [],
        // 培训材料
        materialList: [],
        // 题库
        topicArray: [
          {
            questionOptions: [],
            answer: []
          }
        ]
      };
      this.cfdiaVisible = true;
    },
    // 查看课程
    viewCourse(row) {
      console.log(row);
    },
    // 编辑课程
    editCourse(row) {
      console.log(row);
    },
    // 删除课程
    deleteCourse(row, index) {
      console.log(row, index);
    },
    // 保存成功
    onFormSubmit(data) {
      if (data.isNew) {
        // 新增
        this.invCheckoutList.unshift({});
        this.$set(this.invCheckoutList, 0, data);
        this.totalNum = this.totalNum + 1;
      } else {
        const index = this.invCheckoutList.findIndex(item => item.orderNo === data.orderNo);
        this.$set(this.invCheckoutList, index, data);
      }
    },
  }
};
</script>

<style lang="sass">
@import "../../../../styles/utils"
$SEARCHHEIGHT: 106px
$PAGEHEIGHT: 56px
$SELECTWIDTH: 100px
$TREEWIDTH: 360px
$PADDINGWIDTH: 12px
.cp-manage-train-courseman
  .left-wrap
    position: absolute
    top: $PADDINGWIDTH
    left: 16px
    bottom: $PADDINGWIDTH
    width: $TREEWIDTH
    background-color: #fff
    .tree-title
      position: relative
      height: 40px;
      line-height: 40px;
      background: #f5f7fa;
      margin: 0;
      padding-left: 15px;
      border: 1px solid #ebeef5;
      box-sizing: border-box;
      color: #606266;
      .right-btn
        position: absolute
        right: 16px
        line-height: 40px
        .icon-act
          font-size: 20px
    .el-tree
      height: calc(100% - 44px)
      overflow-x: hidden
      overflow-y: auto
    .el-tree-node__content
      height: 34px
    .el-tree-node:focus>.el-tree-node__content, .el-tree-node__content:hover
      background-color: transparent
    .custom-tree
      flex: 1
      display: flex
      align-items: center
      justify-content: space-between
      font-size: 14px
      padding-right: 8px
      height: 32px
      line-height: 32px
      .el-input
        max-width: 150px
      .icon-act
        font-size: 16px
        font-weight: 500
        cursor: pointer
        margin-left: 3px
        margin-right: 3px
        &:hover
          color: #5D9BFB
      .ml
        margin-left: 14px
      .active
        color: #5D9BFB
  .right-wrap
    position: absolute
    top: 0
    right: 16px
    bottom: 0
    left:  $TREEWIDTH + 32px
    .mancou-search
      height: 106px
      padding: 12px 0 12px 0
      overflow-x: auto
      overflow-y: hidden
      @media screen and (min-width: 1920px)
        height: 56px
      .select-width
        width: $SELECTWIDTH
      .date-width
        width: 260px
      .el-form-item
        margin-right: 14px
      .el-form-item__label
        margin-left: 6px
        padding-right: 6px
      .el-date-editor .el-range__close-icon
        width: 20px
      .el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label
        height: 32px
    .mancou-table
      position: absolute
      top: 106px
      bottom: $PAGEHEIGHT
      left: 0
      right: 0
      overflow-x: hidden
      overflow-y: auto
      &::before
        display: none
      @media screen and (min-width: 1920px)
        top: 56px
    .el-table
      th, td
        text-align: center
    .mancou-pagination
      position: absolute
      bottom: 12px
      left: 0
      right: 0
      text-align: center
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: 3px
    margin-right: 3px
    &:hover
      color: #5D9BFB
</style>
